package com.leil.movies.spider;

import com.leil.movies.project.rest.handler.DouBanApiErrorHandler;
import com.leil.movies.project.service.impl.MovieServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.nio.charset.Charset;
import java.util.LinkedList;

public class MovieSpiderRunnable implements Runnable {

    private final Logger logger = LoggerFactory.getLogger(MovieSpiderRunnable.class);

    // 每页条目数量
    final static int PAGE_COUNT = 20;

    private static LinkedList<RestTemplate> restTemplateQueue = new LinkedList<>();

    private final String genres;

    private final MovieServiceImpl movieService;

    public MovieSpiderRunnable(String genres, MovieServiceImpl movieService) {
        this.genres = genres;
        this.movieService = movieService;
    }

    private static RestTemplate restTemplateBuilder() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000);
        factory.setConnectTimeout(5000);
//        factory.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("123.169.165.139", 9999)));
        RestTemplate restTemplate = new RestTemplate(factory);
        restTemplate.setErrorHandler(new DouBanApiErrorHandler());
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("UTF-8")));
        return restTemplate;
    }

    public static synchronized RestTemplate getRestTemplate() {
        if (restTemplateQueue.isEmpty()) {
            return restTemplateBuilder();
        }
        return restTemplateQueue.poll();
    }

    public static void addRestTemplateToQueue(RestTemplate restTemplate) {
        restTemplateQueue.add(restTemplate);
    }

    @Override
    public void run() {
        logger.info("【" + Thread.currentThread().getName() + "】" + "开始执行：" + genres);
        RestTemplate restTemplate = MovieSpiderRunnable.getRestTemplate();
        MovieSpiderProcessor movieSpiderProcessor = new MovieSpiderProcessor(restTemplate);
        movieSpiderProcessor.setMovieService(movieService);
        int index = 0;
        int count = 20;
        while (count >= 20) {
            int start = PAGE_COUNT * index;
            count = movieSpiderProcessor.process(genres, start);
            index++;
        }

        MovieSpiderRunnable.addRestTemplateToQueue(restTemplate);
        logger.info("【" + Thread.currentThread().getName() + "】" + " genres : 执行完毕！");
    }

}
